package com.ytc.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ytc.basic.domain.Category;
import com.ytc.basic.mappers.CategoryMapper;
import com.ytc.basic.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ytc.commons.model.vo.CategoryVo;
import com.ytc.commons.model.vo.ResponseResult;
import com.ytc.commons.utils.BeanHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 *
 * @since 2023-04-01
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public ResponseResult<CategoryVo> findTreeNodes() {
        //1.查询1级课程分类，根据parentid查询，查询数据==0
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper();
        qw.eq(Category::getParentid,"0");
        Category oneCategory = this.getOne(qw); //一级的课程，所有课程分类的老大只有一个

        CategoryVo vo1 = BeanHelper.copyProperties(oneCategory,CategoryVo.class);//把oneCategory的数据装到vo里面，方便返回给前端

        //2.查询课程二级分类，根据parentId查询，查询数据为1级课程id
        LambdaQueryWrapper<Category> qww = new LambdaQueryWrapper<>();
        qww.eq(Category::getParentid,oneCategory.getId());
        List<Category> twosCategory = this.list(qww); //因为二级是老大管理的，不止一个，所以用List接收
        List<CategoryVo> vo2 = BeanHelper.copyWithCollection(twosCategory, CategoryVo.class);  //二级课程类型的vo对象
        for(CategoryVo categoryVo:vo2){
            //遍历二级目录之后查询三级，并且封装到2级里面
            LambdaQueryWrapper<Category> qwww = new LambdaQueryWrapper<>();
            qwww.eq(Category::getParentid,categoryVo.getId());
            List<Category> threesCategory = this.list(qwww);
            List<CategoryVo> vos3 = BeanHelper.copyWithCollection(threesCategory,CategoryVo.class);
            categoryVo.setCategoryTreeNodes(vos3);
        }

        //最最后,把2级课程类型装到1级里面，并且返回给前端
        vo1.setCategoryTreeNodes(vo2);

        return ResponseResult.okResult(vo1);
    }
}
